#ifndef ENTITY_MANAGER
#define ENTITY_MANAGER

#include <cassert>
#include <ctime>
#include <map>

#include "BaseEntity.h"
#include "Entity/Game/Prey.h"
#include "Types/AITypes.h"


class BaseEntity;

class EntityManager
{
private:
	typedef std::map<AITypes::EntityID, BaseEntity*> EntityMap;
	EntityMap m_entityMap;

private:
	EntityManager() {};
	EntityManager(const EntityManager&) {};
	EntityManager& operator=(const EntityManager&) {};

public:
	static EntityManager& GetInstance();
	void RegisterEntity(BaseEntity* entity);
	BaseEntity* GetEntityFromID(AITypes::EntityID id) const;
	void RemoveEntity(AITypes::EntityID id);
	void RemoveEntity(BaseEntity* entity);
	
	//todo: need to find a better way to do this, store the typeid in the typedef perhaps
	//Not very reliable
	template <class T>
	BaseEntity* GetRandomEntityOfType()
	{
		//This is all bad and dangerous!
		srand((unsigned int)time(0));

		EntityMap::const_iterator it = m_entityMap.begin();

		for (unsigned int retry = 0; retry < m_entityMap.size() * m_entityMap.size(); retry++)
		{
			std::advance(it, rand() % m_entityMap.size());

			if (dynamic_cast<T*>(it->second) != NULL)
			{
				return it->second;
			}
		}

		//random failed search the list one last time before returning null
		for (EntityMap::const_iterator it = m_entityMap.begin(); it != m_entityMap.end(); ++it)
		{
			if (dynamic_cast<T*>(it->second) != NULL)
			{
				return it->second;
			}
		}

		return NULL;
	}
};

#endif